

from fastapi import APIRouter
import requests
from xtquant import xtdata

from router import return_json
from utils.format import format_info
from utils.stock import get_stock_list

router = APIRouter()

sorted_info_list=[]




def callback(ticks):
    info_list=[]
    sorted_info_list=[]
    for code in ticks:
        type_dict=xtdata.get_instrument_type(code)
        if type_dict.get("stock")==True:
            info=xtdata.get_instrument_detail(code,True)
            info_list.append({
                "exchangeId":info.get("ExchangeID"),
                "instrumentId":info.get("InstrumentID"),
                "instrumentName":info.get("InstrumentName"),
                "productId":info.get("ProductID"),
                "productName":info.get("ProductName"),
                "exchangeCode":info.get("ExchangeCode"),
                "uniCode":info.get("UniCode"),
                "createDate":info.get("CreateDate"),
                "openDate":info.get("OpenDate"),
                "expireDate":info.get("ExpireDate"),
                "floatVolume":info.get("FloatVolumn"),
                "totalVolume":info.get("TotalVolumn"),
            })
                
        if len(info_list)>5500:
           sorted_info_list = sorted(info_list, key=lambda x: x['uniCode'])
    return sorted_info_list        


@router.post("/update/remote")
def update_remote_info():
    
    try:
        requests.post('http://www.qmt.zj.cn:8888/info/save/all',json={"infos":sorted_info_list})
        print(f"更新QMT基本信息成功")
    except:
        print(f"全量更新QMT基本信息失败")
   
    xtdata.subscribe_whole_quote(code_list=["SH","SZ","BJ"],callback=callback)


@router.get("/get/all")
def get_all_info():
    stock_list=sorted(get_stock_list())
    info_list=[]
    for code in stock_list:
        type_dict=xtdata.get_instrument_type(code)
        if type_dict.get("stock")==True:
            info=xtdata.get_instrument_detail(code,True)
            info_list.append(format_info(info))
    return return_json(info_list)